/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.jrk_verwaltung.security.login;

import de.jrk_verwaltung.security.login.stats.CFailureThreeTriesState;
import de.jrk_verwaltung.security.login.stats.CNotLogOnState;
import de.jrk_verwaltung.security.login.stats.ILoginState;
import de.jrk_verwaltung.security.login.view.actions.CCancelLoginAction;
import de.jrk_verwaltung.security.login.view.actions.CLoginAction;
import de.jrk_verwaltung.security.login.view.frmLogin;
import javax.persistence.EntityManagerFactory;
import javax.swing.AbstractAction;

/**
 * 
 * @author JRK-FO
 */
public final class CLoginController {
    private final CLoginModel loginModel;
    private final frmLogin loginView;
    private final CLoginAction loginAction;
    private final AbstractAction cancelLoginAction;
    private final Integer MAX_TRIES = 3;
    private Integer loginTries;
    private ILoginState loginState = new CNotLogOnState();

    public CLoginController(final EntityManagerFactory emf) {
        this.loginTries = 0;
        this.loginModel = new CLoginModel(emf);
        this.loginState = new CNotLogOnState();
        this.loginAction = new CLoginAction(this);
        this.cancelLoginAction = new CCancelLoginAction(this);
        this.loginView = new frmLogin(null, true, this);
    }

    public void login() {

        if (loginTries < MAX_TRIES) {
            final String str = new String(this.loginView.getPassword());
            loginState = loginModel.login(this.loginView.getUser(), str);
            loginTries++;
        } else if (loginTries.equals(MAX_TRIES)) {
            loginState = new CFailureThreeTriesState();
            loginTries++;
        } else if (loginTries > MAX_TRIES) {
            loginState = new CNotLogOnState();
        } else {
            loginState = new CNotLogOnState();
        }
        loginState.executeState(this);
    }

    public final void cancelLogin() {
        this.loginView.closeView();
    }

    public void showLoginDialog() {

        loginView.setVisible(true);
    }

    public AbstractAction getCancelLoginAction() {
        return cancelLoginAction;
    }

    public CLoginAction getLoginAction() {
        return loginAction;
    }

    public void showLoginFaultHint(String stateText) {
        loginView.showLoginFaultHint(stateText);
    }
}
